package hot;

import java.util.Deque;
import java.util.LinkedList;

public class Num394 {
    public String decodeString(String s) {
        StringBuilder sb = new StringBuilder();
        Deque<String> stack_string = new LinkedList<>();
        Deque<Integer> stack_num = new LinkedList<>();
        int num = 0;
        for(Character c: s.toCharArray()) {
            if(c == '[') {
                stack_num.push(num);
                stack_string.push(sb.toString());
                num = 0;
                sb = new StringBuilder();
            }else if(c == ']') {
                int sum = stack_num.pop();
                StringBuilder tmp = new StringBuilder();
                for(int i = 0; i < sum; i++) {
                    tmp.append(sb);
                }
                sb = new StringBuilder(stack_string.pop() + tmp);
            }else if(c - '0' >= 0 && c - '0' <= 9) {
                num = num * 10 +(c - '0');
            }else {
                sb.append(c);
            }
        }
        return sb.toString();
    }
}
